<template>
  <div>
    <el-breadcrumb separator-class="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="openAddRoleDialog()">添加</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolelist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名" prop="roleName"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-tag v-if="scope.row.delState==0" type="success" size="mini">正常</el-tag>
            <el-tag v-else type="danger" size="mini">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template v-slot="scope">
            <div v-if="scope.row.delState===0">
              <el-tooltip
                class="item"
                effect="dark"
                content="修改"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  icon="Edit"
                  size="mini"
                  @click="openEditRoleDialog(scope.row.roleId)"
                >修改</el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="禁用"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  icon="Delete"
                  size="mini"
                  @click="disableRole(scope.row.roleId)"
                >禁用</el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="设置权限"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="Setting"
                  size="mini"
                  @click="openSettingPowerDialog(scope.row)"
                >设置</el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      v-model="addRoleDialogVisible"
      width="30%"
      @close="resetAddRoleForm()"
    >
      <el-form
        ref="addRoleFormRef"
        :model="addRoleForm"
        :rules="addRoleFormRules"
        label-width="0px"
      >
        <!-- 角色名称 -->
        <el-form-item prop="roleName">
          <el-input
            v-model="addRoleForm.roleName" 
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      v-model="editRoleDialogVisible"
      width="30%"
      @close="resetEditRoleForm()"
    >
      <el-form
        ref="editRoleFormRef"
        :model="editRoleForm"
        :rules="editRoleFormRules"
        label-width="0px"
      >
        <!-- 角色名称 -->
        <el-form-item prop="roleName">
          <el-input
            v-model="editRoleForm.roleName" 
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置权限对话框 -->
    <el-dialog
      title="设置权限"
      v-model="powerDialogVisible"
      width="40%"
    >
      <span>
        <el-tree
          :data="functions"
          :props="functionsTreeProps"
          node-key="id"
          :default-checked-keys="oldLeafPowers"
          show-checkbox
          default-expand-all
          ref="functionsTreeRef"
        ></el-tree>
      </span>      
      <span slot="footer" class="dialog-footer">
        <el-button @click="powerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePower">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script setup>
 import { ref, reactive, getCurrentInstance ,onMounted} from "vue";
    const { proxy } = getCurrentInstance();
    // 封装添加角色表单数据
    const addRoleForm = reactive({
      roleName: ""
    });
    // 封装修改角色表单数据
    const editRoleForm = reactive({
      roleId: "",
      roleName: ""
    });
    // 指定添加角色表单被引用时的名称和标识
    const addRoleFormRef = ref(null);
    // 指定修改角色表单被引用时的名称和标识
    const editRoleFormRef = ref(null);
    // 设置添加角色表单验证规则
    const addRoleFormRules = reactive({
      roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
    });
    // 设置修改角色表单验证规则
    const editRoleFormRules = reactive({
      roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
    });
    // 控制添加角色对话框是否可见
    const addRoleDialogVisible = ref(false);
    // 控制修改角色对话框是否可见
    const editRoleDialogVisible = ref(false);

    // 角色列表
    const rolelist = ref(null);

    // 向后台程序发送请求，获取角色列表
    const getRoles = async () => {
      // 获取角色列表
      const { data: res } = await proxy.$axios.get("roles");
      if (res.code != 0) return proxy.$message.error("没有角色记录!");
      rolelist.value = res.data;
    };
    
     // 控制设置权限对话框是否可见
    const powerDialogVisible = ref(false);
    // 保存系统功能菜单列表
    const functions = ref(null);
    // 保存用于设置权限的树形控件prop属性的配置选项
    const functionsTreeProps = reactive({
      label: "text",
      children: "children"
    });

    // 原有权限叶子节点id
    const oldLeafPowers = ref(null);

    // 指定设置权限的树形控件被引用时的名称和标识
    const functionsTreeRef = ref(null);

    // 角色id
    const roleId = ref(0);

    // 打开设置权限对话框
    const openSettingPowerDialog = async role => {
      oldLeafPowers.value=[];
      roleId.value = role.roleId;
      // 获取所有功能菜单列表
      const { data: res1 } = await proxy.$axios.get("functions");
      functions.value = res1.data[0].children;
      // 获取该管理员原有的功能菜单列表
      const { data: res2 } = await proxy.$axios.get("getLeafFunctionsByRid", {
        params: {
          roleId: roleId.value
        }
      });
      oldLeafPowers.value = res2;
      await nextTick();
      powerDialogVisible.value = true;
    };

    // 保存权限
    const savePower = async () => {
      const newPowers = [
        ...functionsTreeRef.value.getCheckedKeys(),
        ...functionsTreeRef.value.getHalfCheckedKeys()
      ];
      const fids = newPowers.join(",");
      console.log(fids);
      const { data: res } = await proxy.$axios.post(`roles/${roleId.value}`, {
        fids: fids
      });
      if (res.code !== 0) return proxy.$message.error("设置权限失败!");
      proxy.$message.success("设置权限成功!");
      powerDialogVisible.value = false;
    };

    // 打卡添加角色对话框
    const openAddRoleDialog = () => {
      addRoleDialogVisible.value = true;
    };

    // 重置添加角色对话框中的表单
    const resetAddRoleForm = () => {
      addRoleFormRef.value.resetFields();
    };

    // 重置修改角色对话框中的表单
    const resetEditRoleForm = () => {
      editRoleFormRef.value.resetFields();
    };

    // 添加角色
    const addRole = () => {
      addRoleFormRef.value.validate(async valid => {
        if (!valid) return;
        var roleName = addRoleForm.roleName;
        // 判断角色名称是否已存在
        const { data: res1 } = await proxy.$axios.get(`roles/roleName/${roleName}`);
        if (res1.code !== 0) return proxy.$message.error("该角色名称已存在!");
        const { data: res2 } = await proxy.$axios.post(`roles`, {
          roleName: roleName
        });
        if (res2.code !== 0) return proxy.$message.error("添加失败!");
        proxy.$message.success("添加成功!");
        getRoles();
        addRoleDialogVisible.value = false;
      });
    };

    // 打开修改对话框
    const openEditRoleDialog = async roleId => {
      editRoleDialogVisible.value = true;
      const { data: res } = await proxy.$axios.get(`roles/roleId/${roleId}`);
      // console.log(res.data);
      if (res.code != 0) return proxy.$message.error("获取数据失败!");
      editRoleForm.roleName = res.data.roleName;
      editRoleForm.roleId = res.data.roleId;
    };

    // 修改角色
    const editRole = () => {
      editRoleFormRef.value.validate(async valid => {
        if (!valid) return;
        var roleName = editRoleForm.roleName;
        var roleId = editRoleForm.roleId;
        // 判断角色名称是否已存在
        const { data: res1 } = await proxy.$axios.get(
          `roles/roleName/${roleName}/roleId/${roleId}`
        );
        if (res1.code !== 0) return proxy.$message.error("该角色名称已存在!");
        const { data: res2 } = await proxy.$axios.put(`roles`, {
          roleName: roleName,
          roleId: roleId
        });
        if (res2.code !== 0) return proxy.$message.error("修改失败!");
        proxy.$message.success("修改成功!");
        getRoles();
        editRoleDialogVisible.value = false;
      });
    };

    // 角色禁用
    const disableRole = async roleId => {
      const { data: res } = await proxy.$axios.put(`roles/roleId/${roleId}/delState`);
      if (res.code !== 0) return proxy.$message.error("禁用失败!");
      proxy.$message.success("禁用成功!");
      getRoles();
    };

    onMounted(() => {
      getRoles();
    });

</script>
<style lang="less" scoped>
</style>


